#!/bin/bash

port=6379
redis_server="/opt/redis/bin/redis-server"
data_dir="/data/redis"
config_dir="/opt/redis/conf"

# 判断是否有参数
if [ "$1" == "" ]; then
    echo $0 [port]
    exit 1
fi
# 判断是否是整数
if grep '^[[:digit:]]*$' <<<"$1" >> /dev/null; then
    port=$1
else
    echo 'error port . port range 1000-65536'
    exit 1
fi
# 判断端口是否在合法范围
if [[ $1 -le 1000 || $1 -ge 65535 ]]; then
    echo "error port . port range 1000-65536"
    exit 1
fi

# create random password
random_password=""
arr=(a b c d e f g h i g k l m n o p q r s t u v w x y z
    A B C D E F G H I G K L M N O P Q R S T U V W X Y Z
    ! @ 0 1 2 3 4 5 6 7 8 9)
for ((i = 0; i < 16; i++)); do
    random_password=${random_password}${arr[$RANDOM % ${#arr[@]}]}
done

mkdir -p ${config_dir}
mkdir -p ${data_dir}

cat >${config_dir}/${port}.conf <<EOF
bind 0.0.0.0
protected-mode yes
port ${port}
daemonize yes
pidfile ${data_dir}/redis_${port}.pid
loglevel notice
logfile "${data_dir}/${port}.log"
databases 16
always-show-logo yes
save 900 1
save 300 10
save 60 10000
dbfilename dump_${port}.rdb
dir ${data_dir}
appendonly yes
appendfilename "appendonly_${port}.aof"
appendfsync everysec
requirepass "${random_password}"
EOF
echo -n "Start service command : "
echo "${redis_server} ${config_dir}/${port}.conf"
